

import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;

public class FreehandTool extends Tool {
   
  protected Point startingMousePosition;
  protected LinkedList LineList;
  protected int minx, miny, maxx, maxy;

  public FreehandTool(DrawingCanvas canvas, LinkedList<ShapeObject> ShapeObjects, MDUser mdUser) {
	  super(canvas, ShapeObjects, mdUser);
  }
  
  protected void drawLineSegment(Point p1, Point p2) {
    canvas.getImageBufferGraphics().drawLine(p1.x,p1.y,p2.x, p2.y);
    int x0 = Math.min(p1.x, p2.x);
    int y0 = Math.min(p1.y, p2.y);
    int dx = Math.abs(p2.x - p1.x)+ 1;
    int dy = Math.abs(p2.y - p1.y) + 1;
    canvas.repaint(x0, y0, dx, dy);
  }

 public void mousePressed(MouseEvent e)  {
   startingMousePosition = e.getPoint();
   LineList = new LinkedList<LineObject>();
 }

 public void mouseDragged(MouseEvent e)  {
   Point newMousePosition = e.getPoint();
   drawLineSegment(startingMousePosition,newMousePosition);
   
   if(LineList.isEmpty() || maxx == 0){
	   minx = Math.min(startingMousePosition.x, newMousePosition.x);
	   miny = Math.min(startingMousePosition.y, newMousePosition.y);
	   maxx = Math.max(startingMousePosition.x, newMousePosition.x);
	   maxy = Math.max(startingMousePosition.y, newMousePosition.y);
   }else{
	   int tminx = Math.min(startingMousePosition.x, newMousePosition.x);
	   int tminy = Math.min(startingMousePosition.y, newMousePosition.y);
	   minx = Math.min(minx, tminx);
	   miny = Math.min(miny, tminy);
	   int tmaxx = Math.max(startingMousePosition.x, newMousePosition.x);
	   int tmaxy = Math.max(startingMousePosition.y, newMousePosition.y);
	   maxx = Math.max(maxx, tmaxx);
	   maxy = Math.max(maxy, tmaxy);
   }
   
   
   LineList.add(new LineObject(startingMousePosition, newMousePosition, canvas.penColor));
   startingMousePosition = newMousePosition;
 }

  public void mouseReleased(MouseEvent e) {
	   ShapeObjects.add(new FreehandObject(new Point(minx, miny), 
			   new Point(maxx, maxy), canvas.penColor, LineList));
	   maxx = 0;
	   paintObjects(0);
  }

	public void keyPressed(KeyEvent e) {}
}
